<template>
  <div>
    <page-header-wrapper />
    <a-card
      :loading="loading"
      :title="$t('menu.site.content.form_model_content')"
      style="margin-top: 10px"
    >
      <div>
        <!-- 模型关联外键 -->
        <a-form-item v-if="formInfo.form_bind_model !== '-1'">
          选择分类：
          <a-select
            show-search
            :value="foreign_uuid"
            placeholder="input search text"
            style="width: 100%"
            :default-active-first-option="false"
            :filter-option="false"
            :not-found-content="null"
            @search="fetchModel"
            @change="handleChange"
          >
            <a-select-option v-for="item in selectList" :key="item.uuid">
              {{ item[item.titleField] }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-for="(item, index) in fields" :key="index" v-if="item.form_field_name.substr(0, 2) === 'ex'">
          {{ item.form_field_as_name }}:
          <template v-if="item.form_field_type.toLocaleLowerCase() === 'string'">
            <a-input v-model="data[item.form_field_name]" />
          </template>
          <template v-if="item.form_field_type.toLocaleLowerCase() === 'switch'">
            <a-switch :default-checked="switchList[item.form_field_name]" @change="value => changeValue(item.form_field_name, value, 'switchList')" />
          </template>
          <template v-if="item.form_field_type.toLocaleLowerCase() === 'text'">
            <wang-editor v-model="data[item.form_field_name]" @change="value => changeValue(item.form_field_name, value)" />
          </template>
          <template v-if="item.form_field_type.toLocaleLowerCase() === 'bigint'">
            <a-input-number
              :default-value="data[item.form_field_name]"
              :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => value.replace(/\$\s?|(,*)/g, '')"
              style="width: 180px"
              @change="value => changeValue(item.form_field_name, value)"
            />
          </template>
          <template v-if="item.form_field_type.toLocaleLowerCase() === 'float'">
            <a-input-number
              :step="0.1"
              style="width: 180px"
              :default-value="data[item.form_field_name]"
              @change="value => changeValue(item.form_field_name, value)"
            />
          </template>
          <template v-if="item.form_field_type.toLocaleLowerCase() === 'file' || item.form_field_type.toLocaleLowerCase() === 'filelist'">
            <a-upload
              name="file"
              :before-upload="(file) => {
                return uploadChangeFile(file, item)
              }"
              :remove="(file) => {
                return uploadChangeFile(file, item, true)
              }"
              :file-list="files[item.form_field_name]"
              style="margin-bottom: 10px"
              :ref="item.form_field_name"
            >
              <a-button> <a-icon type="upload" /> 上传文件 </a-button>
            </a-upload>
          </template>
        </a-form-item>
        <!--    是否开启评论功能    -->
        <a-form-item>
          是否开启评论：
          <a-switch v-model="data.reply_enable" @change="value => changeValue('reply_enable', value, 'switchList')" />
        </a-form-item>
      </div>
      <a-form-item style="margin-top:24px">
        <a-button
          size="large"
          type="primary"
          @click="save"
        >{{ $t('submit') }}</a-button>
      </a-form-item>
    </a-card>
    <!--  头像  -->
    <a-card v-if="switchList.reply_enable" style="margin-top: 10px" :title="$t('menu.site.content.form_model_reply_list')">
      <a-skeleton avatar :paragraph="{ rows: 4 }" v-if="replyLoading" />
      <comment v-for="(item, index) in replyList" :key="index">
        <a-popconfirm slot="actions" :title="$t('form.basic-form.confirm.delete')" @confirm="() => deleteReplyInfo(item)">
          <a>删除</a>
        </a-popconfirm>
        <a slot="author">{{ item.nick_name }}</a>
        <a-avatar
          slot="avatar"
          :src="`${BASE_URL}/community/tool/get_file/${item.avatar}`"
          :alt="item.user_name"
        />
        <p slot="content">
          {{ item.reply }}
        </p>
        <comment v-for="(child, i) in item.children" :key="i">
          <a-popconfirm slot="actions" :title="$t('form.basic-form.confirm.delete')" @confirm="() => deleteReplyInfo(child)">
            <a>删除</a>
          </a-popconfirm>
          <a slot="author">{{ child.user_name }}</a>
          <a-avatar
            slot="avatar"
            :src="`${BASE_URL}/community/tool/get_file/${child.avatar}`"
            :alt="child.user_name"
          />
          <p slot="content">
            {{ child.reply }}
          </p>
        </comment>
      </comment>
      <empty v-if="replyList.length === 0" />
      <pagination @change="replyNext" :total="replyTotal" hide-on-single-page show-less-items style="margin-top: 10px" />
    </a-card>
  </div>
</template>

<script>

import {
  getDiyFormInfo,
  getFields,
  addFormContent,
  updateFormContent,
  findForm,
  getBindModelData
} from '@/api/form'

import {
  getReply,
  deleteReply,
  saveFile
} from '@/api/tool'

import { Pagination, Comment, Empty } from 'ant-design-vue'

import { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import WangEditor from '@/components/Editor/WangEditor'

export default {
  data () {
    return {
      searchForm: {
        id: '',
        form_id: ''
      },
      data: {},
      // 文件列表
      files: {},
      // 开关列表
      switchList: {},
      // 字段列表
      fields: [],
      // form标题
      form_title: '',
      loading: true,
      isAdd: false,
      formInfo: [],
      selectList: [],
      foreign_uuid: '',
      replyList: [],
      replyLoading: false,
      BASE_URL: process.env.VUE_APP_API_BASE_URL,
      replyTotal: 0,
      replyPage: 1
    }
  },
  components: {
    PageHeaderWrapper,
    WangEditor,
    Pagination,
    Comment,
    Empty
  },
  computed: {
    token () {
      return this.$store.getters.token
    }
  },
  mounted () {
    this.searchForm.form_id = this.$route.params.form_id
    this.searchForm.id = this.$route.params.id === 'undefined' ? '' : this.$route.params.id
    this.isAdd = this.searchForm.id === ''
    findForm(this.searchForm).then(res => {
      this.formInfo = res.items
      if (!this.isAdd) {
        this._getDiyFormInfo()
      } else {
        this._getFields()
      }
    })
  },
  methods: {
    // 获取模型数据
    _getDiyFormInfo () {
      getDiyFormInfo(this.searchForm).then(res => {
        this.data = res.items
        this._getFields()
      })
    },
    // 获取模型字段
    _getFields () {
      getFields(this.searchForm).then(res => {
        this.fields = res.items
        this.initFields()
        this.getReplyInfo()
        this.loading = false
      })
    },
    // 初始化表单字段
    initFields () {
      this.foreign_uuid = this.data.foreign_uuid
      this.fields.map(e => {
        const type = e.form_field_type.toUpperCase()
        if (type === 'BIGINT' || type === 'INT') {
          this.data[e.form_field_name] = parseInt(this.data[e.form_field_name]) || 0
        } else if (type === 'SWITCH') {
          this.data[e.form_field_name] = this.switchList[e.form_field_name] = this.data[e.form_field_name] !== undefined ? parseInt(this.data[e.form_field_name]) === 1 : false
        } else if (type === 'FLOAT') {
          this.data[e.form_field_name] = parseFloat(this.data[e.form_field_name]) || 0.00
        } else if (type === 'FILE' || type === 'FILELIST') {
          // 处理文件类型
          if (this.data[e.form_field_name] === '-1' || this.data[e.form_field_name] === null) {
            this.files[e.form_field_name] = []
          } else {
            this.files[e.form_field_name] = this.data[e.form_field_name].split(',').map((e, key) => {
              return {
                url: `${this.BASE_URL}/community/tool/get_file/${e}`,
                name: e,
                status: 'done',
                uid: key,
                uuid: e
              }
            })
          }
        } else {
          this.data[e.form_field_name] = this.data[e.form_field_name] ?? ''
        }
      })
    },
    // 更改元数据值
    changeValue (key, value, source = '') {
      if (source !== '') this[source][key] = value
      this.data[key] = value
    },
    save () {
      for (const dataKey in this.data) {
        if (typeof this.data[dataKey] === 'boolean') {
          this.data[dataKey] = this.data[dataKey] ? 1 : 0
        }
      }
      this.data.foreign_uuid = this.foreign_uuid
      this.data.form_id = this.searchForm.form_id
      const info = {
        formContent: {
          content: this.data
        }
      }
      if (this.isAdd) {
        addFormContent(info).then(res => {
          this.searchForm.id = res.items.id
          this.isAdd = false
          this.$message.info(res.msg)
        })
      } else {
        info.formContent.content.id = this.searchForm.id
        updateFormContent(info).then(res => {
          this.$message.info(res.msg)
        })
      }
    },
    fetchModel (value) {
      getBindModelData({
        form_id: this.searchForm.form_id,
        keyword: value
      }).then(res => {
        for (const itemsKey in res.items) {
          res.items[itemsKey].titleField = res.title_field
        }
        this.selectList = res.items
      })
    },
    handleChange (value) {
      this.foreign_uuid = value
    },
    // 上传前置回调
    uploadChangeFile (file, field, remove = false) {
      if (remove) {
        this.data[field.form_field_name] = ''
        this.files[field.form_field_name].map((value, key) => {
          if (value.uid === file.uid) {
            this.files[field.form_field_name].splice(key, 1)
          } else {
            this.data[field.form_field_name] = `${this.data[field.form_field_name]},${value.uuid}`
              .replace(/^,+/, '').replace(/,+$/, '')
          }
        })
        this.$refs[field.form_field_name][0].fileList = this.files[field.form_field_name]
        return true
      }

      saveFile({
        file: file
      }).then(res => {
        this.$message.success(res.msg)
        file.uuid = res.items[0].resources_id
        if (field.form_field_type.toUpperCase() === 'FILE') {
          this.files[field.form_field_name] = [file]
        } else {
          this.files[field.form_field_name].push(file)
        }
        this.data[field.form_field_name] = ''
        this.files[field.form_field_name].map(value => {
          this.data[field.form_field_name] = `${this.data[field.form_field_name]},${value.uuid}`
            .replace(/^,+/, '').replace(/,+$/, '')
        })
      })
      return false
    },
    // 获取评论
    getReplyInfo () {
      getReply({
        form_id: this.searchForm.form_id,
        id: this.data.id,
        page: this.replyPage
      }).then(res => {
        // code ...
        this.replyList = res.items
        this.replyTotal = res.count ? res.count : 0
        this.replyLoading = false
      })
    },
    // 获取下一页评论
    replyNext (page) {
      this.replyPage = page
      this.getReplyInfo()
    },
    // 删除评论
    deleteReplyInfo (data) {
      data.form_id = this.searchForm.form_id
      deleteReply(data).then(res => {
        this.$message[res.code === 200 ? 'success' : 'warning'](res.msg)
        this.getReplyInfo()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
